package com.tencreat.service.account.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.BalanceBusinessType;
import com.tencreat.common.enums.BalanceTypeEnum;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.RabbitSendUtils;
import com.tencreat.common.utils.TenCreatUtil;
import com.tencreat.domain.account.AccountWithdrawAudit;
import com.tencreat.domain.account.AccountWithdrawInfo;
import com.tencreat.domain.account.dto.AdminAuditResultDTO;
import com.tencreat.domain.mall.BalanceChange;
import com.tencreat.domain.mall.vo.AuditResultVO;
import com.tencreat.domain.mall.vo.RrsAuditResultVO;
import com.tencreat.mapper.account.AccountWithdrawAuditMapper;
import com.tencreat.service.account.IAccountWithdrawAuditService;
import com.tencreat.service.account.IAccountWithdrawInfoService;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.IBalanceChangeService;
import com.tencreat.service.mall.IPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 提现记录Service业务层处理
 *
 * @author tencreat
 * @date 2021-11-25
 */
@Service
public class AccountWithdrawAuditServiceImpl extends ServiceImpl<AccountWithdrawAuditMapper, AccountWithdrawAudit> implements IAccountWithdrawAuditService {

    @Resource
    private IBalanceChangeService balanceChangeService;

    @Resource
    private IMallUserService mallUserService;
    @Autowired
    private RabbitSendUtils rabbitSendUtils;
    @Autowired
    private IPayService payService;
    @Autowired
    private IAccountWithdrawInfoService accountWithdrawInfoService;

    /**
     * 查询提现记录
     *
     * @param id 提现记录ID
     * @return 提现记录
     */
    @Override
    public AccountWithdrawAudit selectAccountWithdrawAuditById(ReqIdParam id) {
        return baseMapper.selectById(id.getId());
    }

    /**
     * 查询提现记录列表
     *
     * @param accountWithdrawAudit 提现记录
     * @return 提现记录
     */
    @Override
    public List<AccountWithdrawAudit> selectAccountWithdrawAuditList(AccountWithdrawAudit accountWithdrawAudit) {
        return baseMapper.selectList(Wrappers.query(accountWithdrawAudit));
    }

    /**
     * 新增提现记录
     *
     * @param accountWithdrawAudit 提现记录
     * @return 结果
     */
    @Override
    public int insertAccountWithdrawAudit(AccountWithdrawAudit accountWithdrawAudit) {
        accountWithdrawAudit.setCreateTime(LocalDateTime.now());
        return baseMapper.insert(accountWithdrawAudit);
    }

    /**
     * 修改提现记录
     *
     * @param accountWithdrawAudit 提现记录
     * @return 结果
     */
    @Override
    public int updateAccountWithdrawAudit(AccountWithdrawAudit accountWithdrawAudit) {
        accountWithdrawAudit.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(accountWithdrawAudit);
    }

    /**
     * 批量删除提现记录
     *
     * @param ids 需要删除的提现记录ID
     * @return 结果
     */
    @Override
    public int deleteAccountWithdrawAuditByIds(ReqIdsParam ids) {
        return baseMapper.deleteBatchIds(ids.getId());
    }

    /**
     * 删除提现记录信息
     *
     * @param id 提现记录ID
     * @return 结果
     */
    @Override
    public int deleteAccountWithdrawAuditById(ReqIdParam id) {
        return baseMapper.deleteById(id.getId());
    }

    @Override
    @Lock4j(keys = "#param.id")
    public void auditResult(AdminAuditResultDTO param) {
        AccountWithdrawAudit byId = getById(param.getId());
        if (byId.getResult() != 0) {
            throw new CustomException("状态异常，请刷新后重试");
        }
        byId.setAuditTime(LocalDateTime.now());
        byId.setResult(param.getResult());

        BalanceChange balanceChange = balanceChangeService.getById(byId.getBalanceId());
        if (param.getResult() == 2) {
            rabbitSendUtils.sendBalanceMessage(byId.getUuid(),balanceChange.getChangAmount().abs(),"1",BalanceBusinessType.WITHDRAW_FAIL,"",balanceChange.getId()+"", BalanceTypeEnum.BALANCE);
        }
        //审核通过增加用户提现财务记录
        if(param.getResult() == 1 && byId.getWithdrawType().intValue() == 3){
            // 处理中
            byId.setReceiptStatus(0);
            byId.setChannelType(param.getChannelType());
            if (byId.getSn() == null){
                byId.setSn(TenCreatUtil.getPayNo());
            }
            // 查询银行卡信息
            AccountWithdrawInfo accountWithdrawInfo = accountWithdrawInfoService.lambdaQuery().eq(AccountWithdrawInfo::getUserId, byId.getUuid()).eq(AccountWithdrawInfo::getType,0).oneOpt().orElse(new AccountWithdrawInfo());
            if (accountWithdrawInfo == null){
                throw new CustomException("提现账号不存在");
            }
            if (param.getChannelType() == null || param.getChannelType() ==0){
                // 1-已到账
                byId.setReceiptStatus(1);
                byId.setRemarks("线下付款");
            }
            if (param.getChannelType() ==1) {
                // 调用首信易代付功能
                JSONObject behalf = payService.behalf(accountWithdrawInfo, byId);
                if (behalf != null && !behalf.getString("status").equals("true")) {
                    throw new CustomException("转账失败");
                }
            }else if (param.getChannelType() == 2){
                // 调用连连代付功能
                boolean behalfLian = payService.behalfLian(accountWithdrawInfo, byId);
                if (!behalfLian){
                    throw new CustomException("转账失败");
                }
            }else if (param.getChannelType() == 3){
                // 调用杉德代付
                boolean behalf = payService.sandBehalf(accountWithdrawInfo, byId);
                if (!behalf){
                    throw new CustomException("转账失败");
                }
            }
        }
        updateById(byId);
    }

    @Override
    public IPage<AccountWithdrawAudit> list(AccountWithdrawAudit accountWithdrawAudit) {
        return baseMapper.queryList(new Page<>(accountWithdrawAudit.getPageNum(), accountWithdrawAudit.getPageSize()), accountWithdrawAudit);
    }

    @Override
    public RrsAuditResultVO priceStatistics() {
        return baseMapper.priceStatistics();
    }

    @Override
    public AuditResultVO priceStatisticsV2(){
        BigDecimal auditAmount = baseMapper.auditAmount();
        BigDecimal waitAmount = baseMapper.waitAmount();
        BigDecimal refuseAmount = baseMapper.refuseAmount();
        Integer waitCount = lambdaQuery().eq(AccountWithdrawAudit::getResult,0).count();
        Integer succCount = lambdaQuery().eq(AccountWithdrawAudit::getResult,1).count();
        Integer failCount = lambdaQuery().eq(AccountWithdrawAudit::getResult,2).count();
        int totalCount = (waitCount != null ? waitCount : 0) + (succCount != null ? succCount : 0) + (failCount != null ? failCount : 0);
        AuditResultVO auditResultVO = new AuditResultVO();
        auditResultVO.setAuditAmount(auditAmount);
        auditResultVO.setRefuseAmount(refuseAmount);
        auditResultVO.setWaitAmount(waitAmount);
        auditResultVO.setAuditCount(succCount);
        auditResultVO.setRefuseCount(failCount);
        auditResultVO.setWaitCount(waitCount);
        auditResultVO.setTotalCount(totalCount);

        return auditResultVO;
    }
}
